package com.winning.pmph.service;
import com.alibaba.fastjson.JSON;
import com.winning.pmph.utils.Const;
import com.winning.pmph.vo.EsArticle;
import com.winning.pmph.vo.EsKnowledge;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Service
public class RestHighLevelService {

    @Resource
    private RestHighLevelClient client;

    /**
     * 增加记录
     * @throws IOException
     */
    public boolean insertEsKnowledge(EsKnowledge esKnowledge) {
        IndexRequest indexRequest = new IndexRequest(Const.ES_KNOWLEDGE_INDEX, Const.ES_KNOWLEDGE_TYPE, esKnowledge.getId());
        indexRequest.source(JSON.toJSONString(esKnowledge), XContentType.JSON);// 设置文档内容
        return insert(indexRequest);
    }

    public boolean insertEsArticle(EsArticle esArticle) {
        IndexRequest indexRequest = new IndexRequest(Const.ES_ARTICLE_INDEX, Const.ES_ARTICLE_TYPE, esArticle.getId());
        indexRequest.source(JSON.toJSONString(esArticle), XContentType.JSON);// 设置文档内容
        return insert(indexRequest);
    }

    private boolean insert(IndexRequest indexRequest) {
        try {
            IndexResponse response = client.index(indexRequest);
            return RestStatus.OK.equals(response.status());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除记录
     * @param id 索引数据ID
     * @throws IOException
     */
    public boolean deleteEsKnowledge(String id) {
        DeleteRequest deleteRequest = new DeleteRequest(Const.ES_KNOWLEDGE_INDEX, Const.ES_KNOWLEDGE_TYPE, id);
        return delete(deleteRequest);
    }

    private boolean delete(DeleteRequest deleteRequest) {
        try {
            DeleteResponse response = client.delete(deleteRequest);
            return RestStatus.OK.equals(response.status());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 更新记录信息
     * @param updateRequest 数据
     * @throws IOException
     */
    public boolean update(UpdateRequest updateRequest){
        try {
            UpdateResponse response = client.update(updateRequest);// 执行更新文档
            return RestStatus.OK.equals(response.status());
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

}